<template>
    <el-container class="jxc_sale_to_buy_container">
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="searchForm"
                                @event="handleHeaderEvent">
                    <template slot="left_search">
                        <div class="search_area">
                            <div class="tip">已选 <span class="num">{{ selectionList.length }}</span>个物料</div>
                            <el-button type="success" size="mini" @click="genBuyOrder">生成采购订单</el-button>
                        </div>
                    </template>
                    <template slot="right_search">
                        <div class="search_area">
                            <v-select-bottom v-model="searchForm.client_list" type="clientsDrawer"
                                             :options="clientOptions" @input="getList(true)"
                                             class="w200" />
                        </div>
                        <div class="search_area">
                            <v-select-bottom v-model="searchForm.goods_list" type="custom"
                                             :options="productOptions" @selectEvent="handleSelectBottomEvent"
                                             class="w200" />
                        </div>
                        <div class="search_area">
                            <span class="label">销售日期</span>
                            <el-date-picker v-model="searchForm.order_date" type="daterange" placeholder="请选择日期"
                                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                                            value-format="yyyy-MM-dd" style="width: 210px;"
                                            @change="getList(true)" />
                        </div>
                    </template>
                </headerTemplate>
                <div class="card_content">
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions"
                                      @event="handleTableEvent" />
                </div>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import provide from "@common/mixins/provide";
import clothing from "@jxc/utils/clothing";
import BuyOrderForm from "../components/BuyOrderForm";
import {AES} from "@common/utils/crypto";

export default {
    extends: provide,
    name: "JxcSale2Buy",
    data() {
        const _this = this;
        return {
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            _this.getList(true);
                        },
                    },
                ],
                toolbar_filter: [],
            },
            clientOptions: {
                disabled: false,
                placeholder: '客户选择',
                multiple: true,
                collapseTags: true,
                props: {
                    value: 'sid',
                    label: 'display',
                },
                bottomAction: {
                    permission: 'jxc:relatedParty:save',
                    permissionUrl: '/jxcBaseRelated',
                },
            },
            productOptions: {
                multiple: true,
                placeholder: '物料选择',
                url: _this.$api.API_FindJxcGoodss,
                props: {
                    label: 'name',
                    value: 'sid',
                },
                hideBottomAction: true,
            },
            searchForm: {
                audit_state: '',
                order_date: [],
                client_list: [],
                goods_list: [],
            },
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: 'JxcSale2BuyTable',
                container: '.jxc_sale_to_buy_container',
                multiSelect: true,
                showSummary: true,
                summaryArray: [ "qty" ],
                rowConfig: {
                    keyField: 'sid',
                },
                checkboxConfig: {
                    reserve: true,
                },
                columns: [],
                baseColumns: [
                    {
                        label: "物料名称",
                        prop: "goods_name",
                        align: "center",
                        minWidth: 150,
                    },
                    {
                        label: "货品规格",
                        prop: "spec_info",
                        align: "center",
                        minWidth: 150,
                    },
                    {
                        label: "计量单位",
                        prop: "unit_name",
                        align: "center",
                        width: 90,
                    },
                    {
                        label: "销售单号",
                        prop: "order_code",
                        align: "center",
                        minWidth: 150,
                    },
                    {
                        label: "销售日期",
                        prop: "order_date",
                        align: "center",
                        width: 90,
                    },
                    {
                        label: "客户",
                        prop: "client_display",
                        align: "center",
                    },
                    {
                        label: "销售数量",
                        prop: "qty",
                        align: "center",
                    },
                    {
                        label: "采购信息",
                        prop: "gen_bill_num",
                        align: "center",
                        formatter(row) {
                            // let gen_bill_num = _this.$utils.isEmpty(row.gen_bill_num) ? 0 : row.gen_bill_num;
                            return row.gen_buy_qty4base > 0 ? `已采购：${ row.gen_buy_qty4base }${ row.gen_base_unit_name }` : '未生成';
                        },
                    },
                ],
                pagination: {
                    pageIndex: 1,
                },
            },
        };
    },
    computed: {
        ...mapState('jxc', ['setting']),
    },
    mounted() {
        this.init();
    },
    methods: {
        async init() {
            const _this = this;
            _this.dataList = [];
            await _this.storeDispatch('jxc/initSetting');
            _this.initTableOptions();
            _this.clearSelection();
            _this.getList(true);
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            let pagination = $.extend({}, _this.tableOptions.pagination);
            columns = clothing.resetTableColumns(_this.setting, columns);
            columns.forEach(item => {
                delete item.editRender;
            });
            if (clothing.isClothing(_this.setting)) {
                pagination = false;
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns,
                pagination,
            });
        },
        clearSelection() {
            const _this = this;
            _this.selectionList = [];
            this.$nextTick(() => {
                _this.JxcSale2BuyTable.clearCheckboxRow();
                _this.JxcSale2BuyTable.clearCheckboxReserve();
            });
        },
        handleHeaderEvent(event) {
            const _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        handleSelectBottomEvent(event) {
            if (event.type === 'visibleChange' && !event.value) {
                this.getList(true);
            }
            if (['removeTag', 'clear'].indexOf(event.type) !== -1) {
                this.getList(true);
            }
        },
        getList(query) {
            const _this = this;
            if (query) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            if (clothing.isClothing(_this.setting)) {
                queryData.nopage = '1';
            }
            _this.fetchData(_this.$api.API_FindJxcSaleOrderDetails4Sale2Buy, queryData).then(result => {
                _this.dataList = clothing.transferDetailList(_this.setting, result.data);
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
                _this.$nextTick(() => {
                    _this.initSelection();
                });
            }).catch(() => {
            });
        },
        initSelection() {
            const _this = this;
            if (!_this.JxcSale2BuyTable || !_this.$utils.isNotEmptyList(_this.selectionList)) {
                return;
            }
            let selection = _this.selectionList.map(item => item.sid);
            _this.dataList.forEach(item => {
                if (selection.indexOf(item.sid) !== -1) {
                    _this.JxcSale2BuyTable.setCheckboxRow(item, true);
                }
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                let selectionList = this.JxcSale2BuyTable.getCheckboxRecords();
                let reserveList = this.JxcSale2BuyTable.getCheckboxReserveRecords();
                if (this.$utils.isNotEmptyList(reserveList)) {
                    selectionList = selectionList.concat(reserveList);
                }
                this.selectionList = selectionList;
            }
        },
        genBuyOrder() {
            const _this = this;
            if (!_this.checkSelection(_this.selectionList, true)) {
                return;
            }
            let sale_order_detail_list = (_this.selectionList || []).map(item => item.sid);
            if (clothing.isClothing(_this.setting)) {
                sale_order_detail_list = [];
                (_this.selectionList || []).forEach(item => {
                    let presetSaleMap = item.preset_sale_map || {};
                    Object.keys(presetSaleMap).forEach(key => {
                        if (_this.$utils.isNotEmpty(presetSaleMap[key])) {
                            let values = presetSaleMap[key].split('_');
                            if (values.length === 2 && sale_order_detail_list.indexOf(values[1]) === -1) {
                                sale_order_detail_list.push(values[1]);
                            }
                        }
                    });
                });
            }
            _this.$router.push({
                path: '/jxcBuyOrderDetailSale',
                query: {
                    select: AES.en(JSON.stringify({sale_order_detail_list}))
                },
            });
            // _this.$dialog({
            //     title: '以销定购',
            //     width: '1400px',
            //     component: {
            //         value: BuyOrderForm,
            //         props: {
            //             type: 'sale2buy',
            //             row: {
            //                 sale_order_detail_list,
            //             },
            //         },
            //     },
            //     confirmed() {
            //         _this.getList();
            //     },
            // });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.jxc_sale_to_buy_container {
    width: 100%;
    height: 100%;
    overflow: hidden;

    /deep/ .search_area {
        display: flex;
        align-items: center;
        justify-content: center;

        .tip {
            font-size: 14px;
            padding: 0 10px;

            .num {
                font-size: 16px;
                font-weight: bold;
                padding: 0 5px;
                color: #409EFF;
            }
        }

        .label {
            padding-right: 5px;
        }
    }
}
</style>
